﻿using FlowCanvas;
using FlowCanvas.Nodes;
using LogSystem;
using System.Collections;
using Yoozoo.Managers.ResourceManagerV2.Runtime;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    public class PreloadAsset : LatentActionNodeBase
    {
        public override bool allowRoutineQueueing { get { return false; } }

        private ResLoader _resLoader;
        
        private bool _loaded = false;
        private object _asset;
        
        public IEnumerator Invoke(string resPath)
        {
            if (resPath.Contains("cutscene_prologue"))
            {
                Debug.LogWarning(LogModule.Tutorial, $"序章timeline({resPath})已经在Loading时预加载，不要再使用PreloadAsset命令，该命令卸载的时机有问题");
                yield break;
            }

            _resLoader = ResLoader.Alloc();
            
            _resLoader.Add2Load(resPath, ((success, assetName, asset) =>
            {
                _asset = asset;
                _loaded = true;
            }));
            
            _resLoader.Load();
            while (!_loaded)
            {
                yield return new WaitForOneFrame();
            }
        }

        protected override void OnRegisterDerivedPorts(FlowNode node)
        {
            var p1 = node.AddValueInput<string>("resPath");
            
            node.AddFlowInput("In", (f) => { Begin(Invoke(p1.value), f); });
            node.AddValueOutput("resLoader", () => _resLoader);
            node.AddValueOutput("asset", () => _asset);
        }
        
        public override void OnGraphStoped()
        {
            base.OnGraphStoped();
            _asset = null;
            if (_resLoader!=null)
            {
                _resLoader.Recycle2Cache();
                _resLoader = null;
            }
        }
    }
}
